package com.example.mobiletest.data

import android.content.Context
import com.example.mobiletest.R
import com.example.mobiletest.model.BookingData
import com.example.mobiletest.model.Response
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn

class BookingDataManager(private val context: Context) {

    private val mBookingCache by lazy { BookingCache(context) }
    private val mBookingService by lazy { BookingService(context) }

    val bookingData: Flow<Response<BookingData>> = flow {
        emit(Response.Loading())

        mBookingCache.getCachedData()?.also {
            emit(Response.Success(it))
        }

        if (mBookingCache.shouldRefreshCache()) {
            try {
                val freshData = mBookingService.fetchBookingData()
                mBookingCache.saveDataToCache(freshData)
                emit(Response.Success(freshData))
            } catch (e: Exception) {
                emit(Response.Failure(message = e.message ?: context.getString(R.string.failure)))
            }
        }
    }.flowOn(Dispatchers.IO)
}